package pl.hexar.action.offert;

import java.io.Serializable;
import java.util.Date;
import java.util.EventListener;
import java.util.EventObject;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;

import org.ajax4jsf.event.PushEventListener;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;


import pl.hexar.model.Offert;

@Scope(ScopeType.CONVERSATION)
@Name("offertList")
public class OffertList implements Serializable{

	private static final long serialVersionUID = -8451199213508640001L;

	@In
	EntityManager entityManager;

	@In
	LastOffert lastOffert;

	private Date lastOffertLocal = new Date();
	private String tekst = new String();

	PushEventListener listener;

	@DataModel
	private List<Offert> offerts;

	@Factory("offerts")
	public void initOfferts() {
		lastOffertLocal = lastOffert.getLastModify();
		offerts = entityManager.createQuery("select offert from Offert offert")
				.getResultList();
	}

	public void addListener(EventListener listener) {
		if (this.listener != listener) {
			this.listener = (PushEventListener) listener;
		}
	}

	public void check() {
		System.out.println("AAAAAAAAAAAAAAAAAAAa");

		try {
			System.out.println("CCCCCCCCCCCCCCCCCC");
			listener.onEvent(new EventObject(this));

			System.out.println("DDDDDDDDDDDDDDDDDDDD");
		} catch (Exception e) {
			System.out.println(e);
		}

	}

	public void processUpdates() {
		if (lastOffertLocal.before(lastOffert.getLastModify())) {
			System.out.println("----------------processUpdate" + new Date());
			tekst = "processUpdate" + new Date() + " LastOffert: "
					+ lastOffert.getLastModify();

			offerts = entityManager.createQuery(
					"select offert from Offert offert").getResultList();
			for (Offert o : offerts) {

				System.out.println("List: " + o.getModDate() + " Global: "
						+ lastOffert.getLastModify() + " Local: "
						+ lastOffertLocal);
				if (o.getModDate().after(lastOffertLocal))
					o.setModified(true);

			}
			lastOffertLocal = lastOffert.getLastModify();
		}

	}

	public void setTekst(String tekst) {
		this.tekst = tekst;
	}

	public String getTekst() {
		return tekst;
	}

}